<?php
/*
 * @Author: 李明
 * @Date: 2021-08-17 13:42:27
 * @LastEditTime: 2022-02-08 10:26:13
 * @LastEditors: 李明
 * @Description:
 * @FilePath: /CRM2.0-PHP/app/Http/Controllers/order/OrderPayController.php
 * @山东壹零贰肆信息科技有限公司
 */

namespace App\Http\Controllers\order;

use App\Http\Controllers\app\user\UserController;
use App\Http\Controllers\common\LMReturn;
use App\Http\Controllers\Controller;
use App\Http\Controllers\WeChatService\WeChatServiceUtils;
use App\Models\FamiliesMoneyRecord;
use App\Models\InterestRecord;
use App\Models\Order;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\AllInPay\BankCardAuth;

use function PHPUnit\Framework\isNull;

class OrderPayController extends Controller
{
    /**
     * @description: 订单提醒（查询打款订单）
     * @param {Request} $request
     *
     */
    public function OrderPayList(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        // $worker_id = $tokenInfo['worker_id'];
        $all = $request->all();
        $pageSize = $all['size'] ?? 15;
        $nowTime = date("Y-m-d", strtotime("+3 day"));
        $end_time = $all['end_time'] ?? $nowTime;
        $where = [];
        $where[] = ['is_exit', '2']; // 只查询没有提前中止的记录
        // 1待打款，2打款中，3已打款
        if (isset($all['status'])) {
            $where[] = ["interest_record.status", $all['status']];
            if ($all['status'] == '2') {
                if (!isset($all['end_time'])) {
                    $end_time = '2199-01-01';
                }
            }
        }
        $where[] = ["interest_record.date", "<=", $end_time];
        if (isset($all['start_time'])) {
            $startTime = $all['start_time'];
            $where[] = ["interest_record.date", ">=", $startTime];
        }
        if (isset($all['contract_no'])) {
            $where[] = ["order.contract_no", 'like', '%' . $all['contract_no'] . '%'];
        }
        if ($all['status'] == 3) {
            if (isset($all['user_name'])) {
                $where[] = ["interest_record.user_name", 'like', '%' . $all['user_name'] . '%'];
            }
        } else {
            if (isset($all['user_name'])) {
                $where[] = ["user.name", 'like', '%' . $all['user_name'] . '%'];
            }
        }
        $orderStatusList = ['3', '4', '6']; //订单状态 -1草稿， 1是待付款  2是审核中   3是待生效  4是已生效 5是拒绝  6是已结束
        $infoList = InterestRecord::when($all['status'] == 3, function ($query) {
            return $query->Select(
                'interest_record.id',
                'order.contract_no', // 合同编号
                'order.order_money', // 合同金额
                'order.valid_time', // 生效日期
                'order.contract_end_date', // 到期日期
                'product.long_time as product_long_time', // 投资期限
                'product.name as product_name', // 产品名称
                'interest_record.date', // 当前还款日期
                'interest_record.next_date', // 下期还款日期
                'interest_record.interest', // 本期应还利息 最后一期为本期应还利息加本金
                'interest_record.money', // 本金
                'interest_record.type', // 2为正常期 3为最后一期
                'interest_record.status',
                'interest_record.is_exit', //是否提起终止
                'interest_record.interest_money', //实际打款金额
                'interest_record.interest', // 收益
                'interest_record.payment_amount', // 应付打款金额
                'interest_record.real_time', // 实际打款时间
                'interest_record.user_name', // 用户名称
                'user.id_number', // 用户身份证号
                'worker.name as worker_name', // 客户经理名称
                'interest_record.account_name', // 开户名称
                'interest_record.open_bank as open_name', // 开户行
                'interest_record.bank_num', // 银行卡号
                'interest_record.bank_name', // 银行名称
                'interest_record.update_time',
            )
                ->leftjoin("order", "interest_record.order_id", "=", "order.id")
                ->leftjoin("product", "order.product_id", "=", "product.id")
                ->leftjoin("user", "order.user_id", "=", "user.id")
                ->leftjoin("worker", "order.worker_id", "=", "worker.id");
        })->when($all['status'] != 3, function ($query) {
            return $query->Select(
                'interest_record.id',
                'order.contract_no', // 合同编号
                'order.order_money', // 合同金额
                'order.valid_time', // 生效日期
                'order.contract_end_date', // 到期日期
                'product.name as product_name', // 产品名称
                'product.long_time as product_long_time', // 投资期限
                'interest_record.date', // 当前还款日期
                'interest_record.next_date', // 下期还款日期
                'interest_record.interest', // 本期应还利息 最后一期为本期应还利息加本金
                'interest_record.money', // 本金
                'interest_record.type', // 2为正常期 3为最后一期
                'interest_record.status',
                'interest_record.is_exit', //是否提起终止
                'interest_record.interest_money', //实际打款金额
                'interest_record.payment_amount as payment_amount_round', // 应付打款金额
                'interest_record.interest', // 收益
                'interest_record.real_time', // 实际打款时间
                'user.name as user_name', // 用户名称
                'user.id_number', // 用户身份证号
                'worker.name as worker_name', // 客户经理名称
                'bank_card.account_name as account_name', // 开户名称
                'bank_card.bank_sum_name as open_name', // 开户行
                'bank_card.bank_num', // 银行卡号
                'bank.bank_name', // 银行名称
                'interest_record.update_time',
            )
                ->leftjoin("order", "interest_record.order_id", "=", "order.id")
                ->leftjoin("product", "order.product_id", "=", "product.id")
                ->leftjoin("user", "order.user_id", "=", "user.id")
                ->leftjoin("worker", "order.worker_id", "=", "worker.id")
                ->leftjoin("bank_card", "order.bank_card_id", "=", "bank_card.id")
                ->leftjoin("bank", "bank_card.bank_id", "=", "bank.id");
        })
            ->where($where)
            ->whereIn('order.order_status', $orderStatusList)
            ->orderBy("interest_record.date", "desc")
            ->paginate($pageSize);
        $data = json_decode(json_encode($infoList), true);
        foreach ($data['data'] as $key => $value) {
            $date_list = explode(' ', $value['date']);
            if ($date_list) {
                $data['data'][$key]['date'] = $date_list[0];
            }
            $data['data'][$key]['interest_round'] = round($value['interest'], 0);
            $data['data'][$key]['payment_amount'] = $value['money'] + $value['interest'];
            if (isset($value['next_date'])) {
                $next_date_list = explode(' ', $value['next_date']);
                if ($next_date_list) {
                    $data['data'][$key]['next_date'] = $next_date_list[0];
                }
            }
            if (isset($value['real_time'])) {
                $real_date_list = explode(' ', $value['real_time']);
                if ($real_date_list) {
                    $data['data'][$key]['real_time'] = $real_date_list[0];
                }
            }
        }
        return LMReturn::Success($data);
    }
    /**
     * @description: 待打款改为打款中（财务）
     * @param {Request} $request
     *
     */
    public function OrderPayCaiWu(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        try {
            $all = $request->all();
            $interest_id = $all['order_interest_id'];
            $interest_record = InterestRecord::where('id', $interest_id)->with('order')->first();
            if ($interest_record['order']['user_id'] == null || $interest_record['order']['bank_card_id'] == null) {
                return LMReturn::updateErr('订单无客户或银行卡信息，请添加后操作');
            }
        } catch (\Throwable $th) {
            return LMReturn::Error('请检查传参，或者记录不存在', 'OPC004');
        }
        if (isset($all['receivable_type']) && $all['receivable_type'] == 2) {
            $receivable = BankCardAuth::ReceivableFun($interest_id);
            if ($receivable != 1) {
                return LMReturn::Error($receivable);
            }
        } else {
            $interest_record->receivable_type = 1;
        }
        try {
            DB::beginTransaction(); //开启事务
            if ($interest_record->status != 1) {
                DB::rollback(); //数据库回滚
                $order_record = OrderRecordController::intert_order_reocrd_interest_record($interest_record, $tokenInfo, '0', '2', '打款状态异常导致打款失败');
                return LMReturn::Error('打款状态异常', 'OPCBOPC1', $order_record);
            }
            $interest_record->status = 2;
            $interest_record->save();
            $order_record = OrderRecordController::intert_order_reocrd_interest_record($interest_record, $tokenInfo, 5);
            DB::commit(); //提交至数据库
            return LMReturn::Success($order_record);
        } catch (\Throwable $th) {
            DB::rollback(); //数据库回滚
            $order_record = OrderRecordController::intert_order_reocrd_interest_record($interest_record, $tokenInfo, 5, '2');
            return LMReturn::Error('订单进入打款状态失败', 'OPC005', $order_record);
        }
    }
    /**
     * @description: 批量财务
     * @param {Request} $request
     * @return {*}
     */
    public function batch_order_pay_caiwu(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        try {
            $all = $request->all();
            $i_id_list = $all['i_id_list'];
        } catch (\Throwable $th) {
            return LMReturn::Error('传参错误，请检查传参', 'OPC001');
        }
        try {
            DB::beginTransaction(); //开启事务
            $order_records = [];
            foreach ($i_id_list as $i_id) {
                $interest_record = InterestRecord::where('id', $i_id)->with('order')->first();
                if ($interest_record->status != 1) {
                    DB::rollback(); //数据库回滚
                    $order_record = OrderRecordController::intert_order_reocrd_interest_record($interest_record, $tokenInfo, '0', '2', '打款状态异常导致打款失败');
                    return LMReturn::Error('打款状态异常', 'OPCBOPC1', $order_record);
                }
                $interest_record->status = 2;
                $interest_record->save();
                if ($interest_record['order']['user_id'] == null || $interest_record['order']['bank_card_id'] == null) {
                    $order_record['order_id'] = $interest_record->order_id;
                    $order_record['audit_step'] = 0;
                    $order_record['worker_id'] = $tokenInfo['worker_id'];
                    $order_record['type'] = 6;
                    $order_record['ir_id'] = $interest_record->id;
                    $order_record['is_success'] = 2;
                    $order_record['remark'] = '该记录订单无客户或银行卡信息，请添加后操作';
                } else {
                    $order_record = OrderRecordController::intert_order_reocrd_interest_record($interest_record, $tokenInfo, 7);
                }
                $order_records[] = $order_record;
            }
            DB::commit(); //提交至数据库
            return LMReturn::Success($order_records);
        } catch (\Throwable $th) {
            DB::rollback(); //数据库回滚
            return LMReturn::Error('发生错误，请通知管理员OPC002', 'OPC002');
        }
    }
    /**
     * @description: 打款中改为已打款（出纳）
     * @param {Request} $request
     *
     */
    public function OrderPayChuNa(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        try {
            $all = $request->all();
            $worker_id = $tokenInfo['worker_id'];
            $interest_id = $all['order_interest_id'];
            $pay_list = $all['pay_list'] ?? [];
            if (count($pay_list) != 1) {
                return LMReturn::Error('传递的付款方式存在问题，请检查', 'OPCOPC1');
            }
            $interest_money = $pay_list[0]['money'];
            $pay_type = $pay_list[0]['pay_type'] ?? 5;/*1银行转账  2pos刷卡  3转存  4通联 5公对私 6公对公*/
            // $pay_type = $all['pay_type'] ?? 5;
            // $interest_date = $all['real_time'] ?? date('Y-m-d', time());
            $interest_record = InterestRecord::where('id', $interest_id)->with('order.bank_card.bank')->with('order.user')->first();
            // 到账银行部分

        } catch (\Throwable $th) {
            return LMReturn::Error('请检查传参，或者记录不存在', 'OPC006');
        }

        try {
            DB::beginTransaction(); //开启事务
            if ($interest_record->status != 2) {
                DB::rollback(); //数据库回滚
                $order_record = OrderRecordController::intert_order_reocrd_interest_record($interest_record, $tokenInfo, '0', '2', '打款状态异常导致打款失败');
                return LMReturn::Error('打款状态异常', 'OPCBOPC1', $order_record);
            }
            if ($interest_record->receivable_type == 2) {
                return LMReturn::Error('已通过线上进行回款，无需操作，目前状态回款中，回款成功后在已打款中查看');
            }
            $interest_record->status = 3;
            $interest_record->interest_money = $interest_money;
            $interest_record->real_time = $pay_list[0]['real_time'];
            $interest_record->bank_num = $interest_record['order']['bank_card']['bank_num'];
            $interest_record->open_bank = $interest_record['order']['bank_card']['bank_sum_name'];
            $interest_record->user_name = $interest_record['order']['user']['name'];
            $interest_record->account_name = $interest_record['order']['bank_card']['account_name'];
            $interest_record->bank_name = $interest_record['order']['bank_card']['bank']['bank_name'];
            $order = $interest_record->order;
            $shouldMoney = $interest_record->money + $interest_record->interest;
            $num = $shouldMoney - $interest_money;

            if ($num < 10.0 && $num > -10.0) {
                if ($interest_record->num == $interest_record->num_all || $interest_record->type == 3) { // 如果是最后一期 处理订单状态 和本金验证
                    $order->order_status = 6;
                    if ($interest_record->money != $order->order_money) { // 本金验证是否一致
                        DB::rollback(); //数据库回滚
                        $order_record = OrderRecordController::intert_order_reocrd_interest_record($interest_record, $tokenInfo, '0', '2', '出纳因为金额异常导致出纳失败');
                        return LMReturn::Error('订单金额异常', 'OPC012', $order_record);
                    }
                }
                $order->save();
                $interest_record->save();
                if (count($pay_list) == 0) {
                    // $real_time = $all['real_time'] ?? $interest_record->date;
                    $pay_dic['course_money'] = 0;
                    $pay_dic['money'] = $interest_money;
                    $pay_dic['pay_type'] = $pay_type;
                    $pay_dic['real_time'] = $pay_list[0]['real_time'];;
                    $pay_list[] = $pay_dic;
                }
                $this->interestPayFamilies($pay_list, $interest_record, $order);
                $order_record = OrderRecordController::intert_order_reocrd_interest_record($interest_record, $tokenInfo, 6);
                DB::commit(); //提交至数据库
//                try {
//                    $contract_no = $interest_record['order']['contract_no'];
//                    $date = $pay_list[0]['real_time'];
//                    $money = UserController::DealMoney($shouldMoney, '4', '1');
//                    $openID = $interest_record['order']['user']['public_open_id'];
//                    $sta = WeChatServiceUtils::SendOrderCollection($contract_no, $openID, $date, $money);
//                } catch (\Throwable $th) {
//                }
                return LMReturn::Success($order_record, '订单打款成功');
            } else {
                DB::rollback(); //数据库回滚
                $order_record = OrderRecordController::intert_order_reocrd_interest_record($interest_record, $tokenInfo, '0', '2', '出纳因为金额不符导致出纳失败');
                return LMReturn::Error('实际打款金额与应打款金额差距过大', 'OPC007', $order_record);
            }
        } catch (\Throwable $th) {
            DB::rollback(); //数据库回滚
            $order_record = OrderRecordController::intert_order_reocrd_interest_record($interest_record, $tokenInfo, 6, '2');
            return LMReturn::Error('订单进入打款状态失败', 'OPC008', $order_record);
        }
    }

    /**
     * @description: 批量回款出纳
     * @param {Request} $request
     * @return {*}
     */
    public function batch_order_pay_chuna(Request $request)
    {
        //去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        try {
            $all = $request->all();
            $i_id_list = $all['i_id_list'];
            //            $worker_id = $all['worker_id'];
            $pay_type = $all['pay_type'] ?? 5;/*1银行转账  2pos刷卡  3转存  4通联 5公对私 6公对公*/
            // 到账银行部分
            $families_id = $all['families_id'] ?? '';
            $money_type = $all['money_type'] ?? 2; //1是  使用取整金额   2 是使用 保留两位小数金额
            $time_type = $all['time_type'] ?? "1";
        } catch (\Throwable $th) {
            return LMReturn::Error('传参错误，请检查传参', 'OPC009');
        }
        $order_records = [];
        try {
            foreach ($i_id_list as $i_id) {
                DB::beginTransaction(); //开启事务
                $interest_record = InterestRecord::where('id', $i_id)->with('order.bank_card.bank')->with('order.user')->first();
                if ($interest_record->status != 2) {
                    DB::rollback(); //数据库回滚
                    $order_record = OrderRecordController::intert_order_reocrd_interest_record($interest_record, $tokenInfo, '0', '2', '打款状态异常导致打款失败');
                    $order_records[] = $order_record;
                    return LMReturn::Error('打款状态异常', 'OPCBOPC1', $order_records);
                }
                $interest_record->status = 3;
                if ($money_type == '1') {
                    $interest_money = $interest_record->payment_amount;
                } elseif ($money_type == '2') {
                    $interest_money = $interest_record->interest + $interest_record->money;
                } else {
                    DB::rollback(); //数据库回滚
                    return LMReturn::Error('发生错误，未知的打款金额', 'OPC010');
                }
                $interest_record->bank_num = $interest_record['order']['bank_card']['bank_num'];
                $interest_record->open_bank = $interest_record['order']['bank_card']['bank_sum_name'];
                $interest_record->user_name = $interest_record['order']['user']['name'];
                $interest_record->account_name = $interest_record['order']['bank_card']['account_name'];
                $interest_record->bank_name = $interest_record['order']['bank_card']['bank']['bank_name'];
                $interest_record->interest_money = $interest_money;
                $order = $interest_record->order;
                $shouldMoney = $interest_record->money + $interest_record->interest;
                $num = $shouldMoney - $interest_money;
                if ($num > -10.0 && $num < 10.0) { // 金额相差不超过十元
                    if ($interest_record->num == $interest_record->num_all || $interest_record->type == 3) { // 如果是最后一期
                        $order->order_status = 6;
                        if ($interest_record->money != $order->order_money) {
                            DB::rollback(); //数据库回滚
                            $order_record = OrderRecordController::intert_order_reocrd_interest_record($interest_record, $tokenInfo, '0', '2', '批量出纳因为金额异常导致出纳失败');
                            $order_records[] = $order_record;
                            return LMReturn::Error('订单金额异常', 'OPC012', $order_records);
                        }
                    }

                    if ($time_type == '1') {
                        $real_time =  $interest_record->date;
                    } else {
                        $real_time = $all['real_time'] ?? $interest_record->date;
                    }

                    $pay_list['families_id'] = $families_id;
                    $pay_list['money'] = $interest_money;
                    $pay_list['course_money'] = 0;
                    $pay_list['pay_type'] = $pay_type;/*1银行转账  2pos刷卡  3转存  4通联 5公对私 6公对公*/
                    $pay_list['real_time'] = $real_time;
                    $interest_record->real_time = $real_time;
                    $this->interestPayFamilies([$pay_list], $interest_record, $order);
                    $interest_record->save();
                    $order->save();
                    $order_record = OrderRecordController::intert_order_reocrd_interest_record($interest_record, $tokenInfo, 8);
                } else {
                    $order_record = OrderRecordController::intert_order_reocrd_interest_record($interest_record, $tokenInfo, '0', '2', '批量打款由于金额不符导致出纳失败');
                }
                DB::commit(); //提交至数据库
                $order_records[] = $order_record;
            }

            return LMReturn::Success($order_records);
        } catch (\Throwable $th) {
            DB::rollback(); //数据库回滚
            return LMReturn::Error('没有全部打款成功，请查看记录', 'OPC011', $order_records);
        }
    }
    /**
     * @description:  生成资金记录
     * @param {*} $pay_list
     * @param {*} $order_id
     * @return {*}
     */
    public static function interestPayFamilies($pay_list, $interest_record, $order)
    {
        $interest_id = $interest_record->id;
        foreach ($pay_list as $pay_dic) {
            $pay = new FamiliesMoneyRecord;
            $pay->interest_id = $interest_id;
            $pay->families_id = $pay_dic['families_id'];
            $pay->order_id = $order->id;
            $pay->worker_id = $order->worker_id;
            $pay->branch_id = $order->branch_id;
            $money = $pay_dic['money'] ?? $interest_record->interest_money;
            $pay->money =  0 - $money;
            $pay->course_money =  $pay_dic['course_money'];
            $pay->pay_type =  $pay_dic['pay_type'];
            $pay->real_time =  $pay_dic['real_time'] ?? $interest_record->real_time;
            $pay->type =  2; // 1订单收款 2还本付息 3费用报销
            $pay->status =  5; // 1审核中  2通过/待打款  3拒绝 4打款中 5已付款
            $pay->save();
        }
    }
}
